package linkedQueue;

/**
 * 自己实现一个单链表 用该链表实现队列*/
public class LinkedQueue implements ILinkedQueueOperation {
    private static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
            this.next = null;
        }
    }

    private ListNode head;
    private ListNode last;
    private int usedSize;

    public LinkedQueue() {
        this.head = null;
        this.last = null;
        this.usedSize = 0;
    }

    @Override
    public boolean offer(int val) {
        ListNode node = new ListNode(val);
        if (this.head == null) {
            this.head = node;
            this.last = node;
        } else {
            this.last.next = node;
            this.last = this.last.next;
        }
        this.usedSize++;
        return true;
    }

    @Override
    public int poll() {
        if (isEmpty()) {
            try {
                throw new MemoryIsEmptyException("队列为空，无法进行删除！ usedSize = " + this.usedSize);
            } catch (MemoryIsEmptyException e) {
                return -1;
            }
        }
        int oldVal = this.head.val;
        this.head = this.head.next;
        this.usedSize--;
        return oldVal;
    }

    @Override
    public int peek() {
        if (isEmpty()) {
            try {
                throw new MemoryIsEmptyException("队列为空，无法进行删除！ usedSize = " + this.usedSize);
            } catch (MemoryIsEmptyException e) {
                return -1;
            }
        }
        return this.head.val;
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public boolean isEmpty() {
        return this.usedSize == 0;
    }
}
